//
//  ScanController.m
//  CMYH
//
//  Created by Loki on 15-5-13.
//  Copyright (c) 2015年 Loki. All rights reserved.
//

#import "ScanController.h"
#import "ZBarSDK.h"
#import "X/X.h"
#import "Busi.h"
#import <QuartzCore/QuartzCore.h>

const NSInteger MSG_OK                              = 1001;
const NSInteger MSG_ERROR                           = 1002;
const NSInteger MSG_MANUALENSURE                    = 1003;
const time_t    TIME_DAY                            = 24 * 60 * 60;


@interface ScanController () <ZBarReaderViewDelegate, BusiDelegate, UIAlertViewDelegate>
@property (nonatomic, strong) ZBarReaderView                        *readerView;
@property (nonatomic, strong) NSTimer                               *timer;

@property (nonatomic, strong) NSString                              *docketNo;
@property (nonatomic, strong) NSString                              *truckNo;
@property (nonatomic, strong) NSString                              *transDate;
@property (nonatomic, strong) NSString                              *transTime;
@property (nonatomic, assign) time_t                                transDatetime;
@property (nonatomic, assign) int                                   limitDay;
@property (nonatomic, assign) time_t                                limitDatetime;
@property (nonatomic, assign) BOOL                                  bScan;

@end

@implementation ScanController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _readerView = [[ZBarReaderView alloc] init];
    _readerView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64);
    _readerView.readerDelegate = self;
    _readerView.allowsPinchZoom = YES;
    _readerView.trackingColor = [UIColor redColor];
    _readerView.tracksSymbols = NO;
    [self.view insertSubview:_readerView belowSubview:_scanCatch];
    
    _scanCatch.layer.borderColor = [UIColor redColor].CGColor;
    _scanCatch.layer.borderWidth = 1;
    _scanCatch.layer.masksToBounds = YES;
    
    if ([XApp isiDevice4]) {
        CGRect rc = _btnScan.frame;
        rc.origin.y -= 88;
        _btnScan.frame = rc;
    }
    
    _limitDay = 0;
    _limitDatetime = 0;
    
    [self getTimeLimit];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)startTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.5
                                              target:self
                                            selector:@selector(moveUpAndDownLine)
                                            userInfo:nil
                                             repeats:YES];
    [_lbTip setHidden:YES];
}


- (void)stopTimer{
    if ([_timer isValid] == YES) {
        [_timer invalidate];
        _timer =nil;
    }
    _line.frame = CGRectMake(_scanCatch.frame.origin.x, _scanCatch.frame.origin.y, _scanCatch.frame.size.width, 1);
    [_lbTip setHidden:NO];
}


//二维码的横线移动
- (void)moveUpAndDownLine {
    CGFloat Y = _line.frame.origin.y;
    if (_scanCatch.frame.origin.y == Y) {
        [UIView beginAnimations:@"asa" context:nil];
        [UIView setAnimationDuration:1];
        _line.frame = CGRectMake(_scanCatch.frame.origin.x, _scanCatch.frame.origin.y + _scanCatch.frame.size.height, _scanCatch.frame.size.width, 1);
        [UIView commitAnimations];
    }
    else {
        [UIView beginAnimations:@"asa" context:nil];
        [UIView setAnimationDuration:1];
        _line.frame = CGRectMake(_scanCatch.frame.origin.x, _scanCatch.frame.origin.y, _scanCatch.frame.size.width, 1);
        [UIView commitAnimations];
    }
    
}

- (IBAction)onScan:(id)sender {
    [_txtDocket resignFirstResponder];
    if (_bScan == false) {
        [self onStartScan];
    }
    else {
        [self onStopScan];
    }
}


- (IBAction)onSearch:(id)sender {
    [_txtDocket resignFirstResponder];
    if (_txtDocket.text.length == 0) {
        [XMsg showToast:@"請先輸入送貨單號碼！"
            withGravity:AlignTop
            andDuration:DurationNormal];
        return;
    }
    
    // 停止扫描
    [self onStopScan];
    
    // 查询单号状态
    [self getProdMasterDataByJobNo:_txtDocket.text];
}


- (void)onStartScan {
    _bScan = true;
    [_btnScan setTitle:@"停止掃描" forState:UIControlStateNormal];
    [_btnScan setTitle:@"停止掃描" forState:UIControlStateHighlighted];
    [_readerView start];
    [self startTimer];
}


- (void)onStopScan {
    _bScan = false;
    [_btnScan setTitle:@"掃描" forState:UIControlStateNormal];
    [_btnScan setTitle:@"掃描" forState:UIControlStateHighlighted];
    [_readerView stop];
    [self stopTimer];
}


- (IBAction)onInput:(id)sender {
    // 停止扫描
    [self onStopScan];
    
    // 跳转到输入送货单
    [self performSegueWithIdentifier:@"gotoInput" sender:self];
}


- (void)getProdMasterDataByJobNo:(NSString*)docketNo {
    // 显示等待
    [XMsg showProgress];
    
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.method = @"GetProdMasterDataByJobNo";
    if (docketNo == nil) {
        NSString *strDocketNo = [_docketNo substringFromIndex:1];
        [req addParam:strDocketNo forKey:@"DocketNo"];
    }
    else {
        self.docketNo = docketNo;
        [req addParam:docketNo forKey:@"DocketNo"];
    }
    [req query];
}


- (void)updateProductRecordState {
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.method = @"UpdateProductRecordState";
    [req addParam:_docketNo forKey:@"DocketNo"];
    [req addParam:[XUser userName] forKey:@"userName"];
    [req addParam:_transDate forKey:@"productDate"];
    [req addParam:[[NSDate date] descriptionOfFormatType:FmtDateTimeDescEn] forKey:@"nowdate"];
    [req addParam:[XUser userName] forKey:@"userName"];
    [req addParam:@"0" forKey:@"isQuality"];
    [req query];
}


- (void)backMismatchingInfo {
    // 显示等待
    [XMsg showProgress];
    
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.method = @"BackMismatchingInfo2";
    [req addParam:_docketNo forKey:@"DocketNo"];
    [req addParam:[XUser stringForKey:@"TruckNo"] forKey:@"inputTruck"];
    [req addParam:[[NSDate date] descriptionOfFormatType:FmtDateTimeDescEn] forKey:@"nowdate"];
    [req addParam:@"3" forKey:@"isQuality"];
    [req query];
}


/**
 * 获取当前时间限制
 * @return
 */
- (void)getTimeLimit {
    // 显示等待
    [XMsg showProgress];
    
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.method = @"GetTimeLimit";
    [req query];
}


#pragma mark 委托通知解码结果。
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image{
    const zbar_symbol_t *symbol = zbar_symbol_set_first_symbol(symbols.zbarSymbolSet);
    NSString *symbolStr = [NSString stringWithUTF8String: zbar_symbol_get_data(symbol)];
    if (symbolStr.length > 0) {
        // 扫描到东西了……
        [self onStopScan];
        
        // 分析内容
        NSArray *arrDatas = [symbolStr componentsSeparatedByString:@"\n"];
        if (arrDatas.count != 9) {
            [XMsg showToast:@"二維碼信息不正確，請重新掃描！"
                withGravity:AlignTop
                andDuration:DurationNormal];
            [self onStartScan];
            return;
        }
        else {
            // 获取 单号、车牌号、日期
            _docketNo = [arrDatas objectAtIndex:0];
            if ([_docketNo characterAtIndex:_docketNo.length - 1] == ' ' || [_docketNo characterAtIndex:_docketNo.length - 1] == '\r') {
                _docketNo = [_docketNo substringToIndex:_docketNo.length - 1];
            }
            
            _truckNo = [arrDatas objectAtIndex:5];
            if ([_truckNo characterAtIndex:_truckNo.length - 1] == ' ' || [_truckNo characterAtIndex:_truckNo.length - 1] == '\r') {
                _truckNo = [_truckNo substringToIndex:_truckNo.length - 1];
            }
            
            _transDate = [arrDatas objectAtIndex:3];
            if ([_transDate characterAtIndex:_transDate.length - 1] == ' ' || [_transDate characterAtIndex:_transDate.length - 1] == '\r') {
                _transDate = [_transDate substringToIndex:_transDate.length - 1];
            }
            
            _transTime = [arrDatas objectAtIndex:4];
            if ([_transTime characterAtIndex:_transTime.length - 1] == ' ' || [_transTime characterAtIndex:_transTime.length - 1] == '\r') {
                _transTime = [_transTime substringToIndex:_transTime.length - 1];
            }
            
            // 处理时间
            struct tm _tm = {0};
            NSArray *arrDate = [_transDate componentsSeparatedByString:@"/"];
            if (arrDate.count != 3) {
                // 不使用 / 拆分，使用 - 拆分
                arrDate = [_transDate componentsSeparatedByString:@"-"];
            }
            if (arrDate.count != 3) {
                [XMsg showToast:@"掃描日期格式有誤！"
                    withGravity:AlignTop
                    andDuration:DurationNormal];
            }
            NSString *strYear = [arrDate objectAtIndex:0];
            NSString *strMonth = [arrDate objectAtIndex:1];
            NSString *strDay = [arrDate objectAtIndex:2];
            if (strYear.length == 2 && strDay.length == 4) {
                // 如果拿到是日月年的方式，倒置年日
                NSString *strTemp = strYear;
                strYear = strDay;
                strDay = strTemp;
            }
            
            NSArray *arrTime = [_transTime componentsSeparatedByString:@":"];
            NSString *strHour = [arrTime objectAtIndex:0];
            NSString *strMinute = [arrTime objectAtIndex:1];
            
            _tm.tm_year = [strYear integerValue] - 1900;
            _tm.tm_mon = [strMonth integerValue] - 1;
            _tm.tm_mday = [strDay integerValue];
            _tm.tm_hour = [strHour integerValue];
            _tm.tm_min = [strMinute integerValue];
            
            _transDatetime = mktime(&_tm);
            
            // 获取时间限制
            [self getProdMasterDataByJobNo:nil];
        }
    }
}


- (void)disposeGetProdMasterDataByJobNo:(NSDictionary*)res {
    if (res == nil) {
        return;
    }
    
    bool bRet = false;
    do {
        NSDictionary *dicEnvelope = [res objectForKey:@"soap:Envelope"];
        if (dicEnvelope == nil) {
            break;
        }
        
        NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
        if (dicBody == nil) {
            break;
        }
        
        NSDictionary *dicResponse = [dicBody objectForKey:@"GetProdMasterDataByJobNoResponse"];
        if (dicResponse == nil) {
            break;
        }
        
        NSDictionary *dicResult = [dicResponse objectForKey:@"GetProdMasterDataByJobNoResult"];
        if (dicResult == nil) {
            break;
        }
        
        NSString *strTruckMatch = [[dicResult objectForKey:@"TruckMatch"] objectForKey:kValue];
        NSString *strTruckCode = [[dicResult objectForKey:@"TruckCode"] objectForKey:kValue];
        NSString *strProDate = [[dicResult objectForKey:@"PDate"] objectForKey:kValue];
        
        // 处理时间
        NSString *strDate = @"";
        NSString *strTime = @"";
        NSArray *arrData = [strProDate componentsSeparatedByString:@" "];
        if (arrData.count == 2) {
            // 获取日期及时间
            strDate = [arrData objectAtIndex:0];
            strTime = [arrData objectAtIndex:1];
        }
        else {
            strDate = [strProDate substringToIndex:10];
            strTime = [strProDate substringFromIndex:11];
        }
        
        // 标识数据已经成功获取
        bRet = true;
        
        // 处理时间
        struct tm _tm = {0};
        NSArray *arrDate = [strDate componentsSeparatedByString:@"/"];
        if (arrDate.count != 3) {
            // 不使用 / 拆分，使用 - 拆分
            arrDate = [strDate componentsSeparatedByString:@"-"];
        }
        if (arrDate.count != 3) {
            [XMsg showToast:@"GetProdMasterDataByJobNo 日期格式有誤！"
                withGravity:AlignTop
                andDuration:DurationNormal];
        }
        NSString *strYear = [arrDate objectAtIndex:0];
        NSString *strMonth = [arrDate objectAtIndex:1];
        NSString *strDay = [arrDate objectAtIndex:2];
        if (strYear.length == 2 && strDay.length == 4) {
            // 如果拿到是日月年的方式，倒置年日
            NSString *strTemp = strYear;
            strYear = strDay;
            strDay = strTemp;
        }
        
        NSArray *arrTime = [strTime componentsSeparatedByString:@":"];
        NSString *strHour = [arrTime objectAtIndex:0];
        NSString *strMinute = [arrTime objectAtIndex:1];
        
        _tm.tm_year = [strYear integerValue] - 1900;
        _tm.tm_mon = [strMonth integerValue] - 1;
        _tm.tm_mday = [strDay integerValue];
        _tm.tm_hour = [strHour integerValue];
        _tm.tm_min = [strMinute integerValue];
        
        time_t tPDate = mktime(&_tm);
        
        if ([strTruckMatch isEqualToString:@"true"]) {
            // 已配对
            NSString *strMsg = [NSString stringWithFormat:@"送貨單：%@\n車牌號：%@\n送貨單已配對！", _docketNo, strTruckCode];
            [XMsg showToast:strMsg withGravity:AlignTop andDuration:DurationNormal];
        }
        else {
            // 未配对
            NSString *strTruckNo = [XUser stringForKey:@"TruckNo"];
            if (tPDate + _limitDay * TIME_DAY < _limitDatetime) {
                // 超时
                NSString *strMsg = [NSString stringWithFormat:@"送貨單：%@\n車牌號：%@\n該票據已超時！", _docketNo, strTruckCode];
                [XMsg showToast:strMsg
                    withGravity:AlignTop
                    andDuration:DurationNormal];
            }
            else if ([strTruckNo isEqualToString:strTruckCode]) {
                // 成功配对
                NSString *strMsg = [NSString stringWithFormat:@"送貨單：%@\n車牌號：%@\n車牌號正確！", _docketNo, strTruckCode];
                [XMsg showToast:strMsg withGravity:AlignTop andDuration:DurationNormal];
                [self updateProductRecordState];
            }
            else {
                // 配对错误！
                NSString *strMsg = [NSString stringWithFormat:@"送貨單：%@\n車牌號：%@\n車牌號錯誤！", _docketNo, strTruckCode];
                [XMsg showToast:strMsg withGravity:AlignTop andDuration:DurationNormal];
                [self backMismatchingInfo];
            }
        }
    } while (0);
    
    // 登陆失败
    if (!bRet) {
        [XMsg showToast:@"送貨單信息獲取失敗！請稍後再試！"
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
}


- (void)disposeGetTimeLimit:(NSDictionary*) res {
    if (res == nil) {
        return;
    }
    
    bool bRet = false;
    do {
        NSDictionary *dicEnvelope = [res objectForKey:@"soap:Envelope"];
        if (dicEnvelope == nil) {
            break;
        }
        
        NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
        if (dicBody == nil) {
            break;
        }
        
        NSDictionary *dicResponse = [dicBody objectForKey:@"GetTimeLimitResponse"];
        if (dicResponse == nil) {
            break;
        }
        
        NSDictionary *dicResult = [dicResponse objectForKey:@"GetTimeLimitResult"];
        if (dicResult == nil) {
            break;
        }
        
        NSString *strLimitDate = [dicResult objectForKey:kValue];
        if (strLimitDate == nil) {
            break;
        }
        
        NSLog(@"limit: %@", strLimitDate);
        
        NSArray *arrData = [strLimitDate componentsSeparatedByString:@","];
        if (arrData.count != 2) {
            break;
        }
        
        _limitDay = [[arrData objectAtIndex:0] integerValue];
        
        NSString *strTemp = [arrData objectAtIndex:1];
        NSString *strDate = @"";
        NSString *strTime = @"";
        NSArray *arrTemp = [strTemp componentsSeparatedByString:@" "];
        if (arrData.count == 2) {
            // 获取日期及时间
            strDate = [arrTemp objectAtIndex:0];
            strTime = [arrTemp objectAtIndex:1];
        }
        else {
            strDate = [strTemp substringToIndex:10];
            strTime = [strTemp substringFromIndex:11];
        }
        
        // 处理时间
        struct tm _tm = {0};
        NSArray *arrDate = [strDate componentsSeparatedByString:@"/"];
        if (arrDate.count != 3) {
            // 不使用 / 拆分，使用 - 拆分
            arrDate = [strDate componentsSeparatedByString:@"-"];
        }
        if (arrDate.count != 3) {
            [XMsg showToast:@"GetTimeLimit 日期格式有誤！"
                withGravity:AlignTop
                andDuration:DurationNormal];
        }
        NSString *strYear = [arrDate objectAtIndex:0];
        NSString *strMonth = [arrDate objectAtIndex:1];
        NSString *strDay = [arrDate objectAtIndex:2];
        if (strYear.length == 2 && strDay.length == 4) {
            // 如果拿到是日月年的方式，倒置年日
            NSString *strTemp = strYear;
            strYear = strDay;
            strDay = strTemp;
        }
        
        NSArray *arrTime = [strTime componentsSeparatedByString:@":"];
        NSString *strHour = [arrTime objectAtIndex:0];
        NSString *strMinute = [arrTime objectAtIndex:1];
        
        _tm.tm_year = [strYear integerValue] - 1900;
        _tm.tm_mon = [strMonth integerValue] - 1;
        _tm.tm_mday = [strDay integerValue];
        _tm.tm_hour = [strHour integerValue];
        _tm.tm_min = [strMinute integerValue];
        
        _limitDatetime = mktime(&_tm);
        bRet = true;
    } while (0);
    
    // 失败
    if (!bRet) {
        [XMsg showToast:@"時間限制信息獲取失敗！請稍後再試！"
            withGravity:AlignTop
            andDuration:DurationNormal];
        [self getTimeLimit];
    }
    
    [self onStartScan];
}


- (void)disposeUpdateProductRecordState:(NSDictionary*) res {
    if (res == nil) {
        return;
    }
    
    bool bRet = false;
    do {
        NSDictionary *dicEnvelope = [res objectForKey:@"soap:Envelope"];
        if (dicEnvelope == nil) {
            break;
        }
        
        NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
        if (dicBody == nil) {
            break;
        }
        
        NSDictionary *dicResponse = [dicBody objectForKey:@"UpdateProductRecordStateResponse"];
        if (dicResponse == nil) {
            break;
        }
        
        NSDictionary *dicResult = [dicResponse objectForKey:@"UpdateProductRecordStateResult"];
        if (dicResult == nil) {
            break;
        }
        
        NSString *strResult = [dicResult objectForKey:kValue];
        if (strResult == nil) {
            break;
        }
        
        bRet = true;
        if ([strResult isEqualToString:@"true"]) {
            [XMsg showToast:@"成功更新送貨單狀態！" withGravity:AlignTop andDuration:DurationNormal];
        }
        else {
            [XMsg showToast:@"送貨單狀態更新失敗！"
                withGravity:AlignTop
                andDuration:DurationNormal];
        }
    } while (0);
    
    // 失败
    if (!bRet) {
        [XMsg showToast:@"時間限制信息！请稍后再试！"
            withGravity:AlignTop
            andDuration:DurationNormal];
        [self getTimeLimit];
    }
    
    [self onStartScan];
}


- (void)disposeBackMismatchingInfo:(NSDictionary*) res {
    if (res == nil) {
        return;
    }
    
    bool bRet = false;
    do {
        NSDictionary *dicEnvelope = [res objectForKey:@"soap:Envelope"];
        if (dicEnvelope == nil) {
            break;
        }
        
        NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
        if (dicBody == nil) {
            break;
        }
        
        NSDictionary *dicResponse = [dicBody objectForKey:@"BackMismatchingInfo2Response"];
        if (dicResponse == nil) {
            break;
        }
        
        NSDictionary *dicResult = [dicResponse objectForKey:@"BackMismatchingInfo2Result"];
        if (dicResult == nil) {
            break;
        }
        
        NSString *strResult = [dicResult objectForKey:kValue];
        if (strResult == nil) {
            break;
        }
        
        bRet = true;
        if ([strResult isEqualToString:@"true"]) {
            [XMsg showToast:@"成功反饋送貨單錯誤信息！" withGravity:AlignTop andDuration:DurationNormal];
        }
        else {
            [XMsg showToast:@"反饋送貨單錯誤信息失敗！" withGravity:AlignTop andDuration:DurationNormal];
        }
    } while (0);
    
    // 失败
    if (!bRet) {
        [XMsg showToast:@"反饋送貨單錯誤信息獲取失敗！請稍後再試！" withGravity:AlignTop andDuration:DurationNormal];
        [self getTimeLimit];
    }
    
    [self onStartScan];
}


#pragma mark BusiDelegate
- (void)requestException:(NSException *)exception withID:(NSString *)reqID {
    if ([reqID isEqualToString:@"GetProdMasterDataByJobNo"]) {
        // 隐藏等待
        [XMsg hideProgress];
        // 显示异常提示
        [XMsg showToast:[NSString stringWithFormat:@"送貨單信息獲取失敗！錯誤原因：%@", [exception reason]]
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
    else if ([reqID isEqualToString:@"UpdateProductRecordState"]) {
        // 显示异常提示
        [XMsg showToast:[NSString stringWithFormat:@"送貨單更新失敗！錯誤原因：%@", [exception reason]]
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
    else if ([reqID isEqualToString:@"BackMismatchingInfo2"]) {
        // 隐藏等待
        [XMsg hideProgress];
        // 显示异常提示
        [XMsg showToast:[NSString stringWithFormat:@"請求修改失敗！錯誤原因：%@", [exception reason]]
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
    else if ([reqID isEqualToString:@"GetTimeLimit"]) {
        [XMsg hideProgress];
        [XMsg showToast:[NSString stringWithFormat:@"獲取限制時間失敗！錯誤原因：%@", [exception reason]]
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
}


- (void)requestFinished:(NSObject *)res withHeaders:(NSDictionary *)headers andID:(NSString *)reqID {
    if ([reqID isEqualToString:@"GetProdMasterDataByJobNo"]) {
        [XMsg hideProgress];
        
        // 处理数据
        [self disposeGetProdMasterDataByJobNo:(NSDictionary*) res];
    }
    else if ([reqID isEqualToString:@"GetTimeLimit"]) {
        [XMsg hideProgress];
        
        // 处理接收数据
        [self disposeGetTimeLimit:(NSDictionary*) res];
    }
    else if ([reqID isEqualToString:@"UpdateProductRecordState"]) {
        [self disposeUpdateProductRecordState:(NSDictionary*) res];
    }
    else if ([reqID isEqualToString:@"BackMismatchingInfo2"]) {
        [XMsg hideProgress];
        
        // 处理接收数据
        [self disposeBackMismatchingInfo:(NSDictionary*) res];
    }
}


@end
